#include <WiFi.h>
#include <Arduino.h>
#include "wifi_manager.h"
#include <config.h>
WiFiClient wifiClient;

// 热点信息
bool isNeedWifiReconnect = false;
bool isWifiConnecting = false;

// 日志打印时间记录
unsigned long lastWifiSendTime = 0;

void wifiInit()
{
  // 初始化 Preferences
  preferences.begin("wifi", false);

  // 读取已有配置，默认返回空字符串
  String ssid = preferences.getString("ssid", "");
  String pwd = preferences.getString("pwd", "");
  String ap_ssid = preferences.getString("ap_ssid", "");
  String ap_password = preferences.getString("ap_password", "");
  String isApEnable = preferences.getString("isEnable", "");

  // 如果对应值为空，说明还没存，就写入默认值
  if (ssid == "")
  {
    preferences.putString("ssid", "Orz");
  }
  if (pwd == "")
  {
    preferences.putString("pwd", "123@qq.com");
  }
  if (ap_ssid == "")
  {
    preferences.putString("ap_ssid", "ESP32_S3_HOTSPOT");
  }
  if (ap_password == "")
  {
    preferences.putString("ap_password", "12345678");
  }
  if (isApEnable == "")
  {
    preferences.putString("isEnable", "true");
  }

  preferences.end();

  if (isApEnable == "true")
  {
    Serial.println("开启 STA + AP 模式");
    // 设置为同时支持 STA + AP 模式
    WiFi.mode(WIFI_AP_STA);
    // 启动热点
    bool ap_ok = WiFi.softAP("ESP32_S3_HOTSPOT", "12345678");
    if (ap_ok)
    {
      Serial.print("热点模式已启用,IP地址:");
      Serial.println(WiFi.softAPIP()); // 默认 192.168.4.1
    }
    else
    {
      Serial.println("热点模式启动失败！");
    }
  }
  else
  {
    WiFi.mode(WIFI_STA);
  }

  // 连接家庭wifi
  wifiCheck();
}

void wifiCheck()
{
  unsigned long now = millis();
  if (now - lastWifiSendTime >= 2000)
  {
    preferences.begin("wifi", true);
    String ssId = preferences.getString("ssid", "");
    String pwd = preferences.getString("pwd", "");
    preferences.end();
    lastWifiSendTime = now;
  }

  if (!isWifiConnecting && (WiFi.status() != WL_CONNECTED || isNeedWifiReconnect))
  {
    preferences.begin("wifi", true);
    String ssId = preferences.getString("ssid", "");
    String pwd = preferences.getString("pwd", "");
    String ap_ssid = preferences.getString("ap_ssid", "");
    String ap_password = preferences.getString("ap_password", "");
    preferences.end();

    // 设置为同时支持 STA + AP 模式
    WiFi.begin(ssId, pwd);
    Serial.println("重新连接中........");
    Serial.print("ssid: ");
    Serial.println(ssId);
    Serial.print("password: ");
    Serial.println(pwd);
    Serial.println("重新连接中........");
    isWifiConnecting = true;
  }

  if (isWifiConnecting)
  {
    if (WiFi.status() == WL_CONNECTED)
    {
      Serial.print("WIFI连接成功,IP地址: ");
      Serial.println(WiFi.localIP());
      isWifiConnecting = false;
      isNeedWifiReconnect = false;
    }
  }
}
